from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse
from .forms import *
from .models import *
from django.contrib.auth.views import auth_login, auth_logout
from user.forms import ArticleForm
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView
from django.urls import reverse_lazy
from main.models import Article, Category


def center(request):
    if request.method == 'POST':
        cuif = UserInfoChangeForm(data=request.POST, files=request.FILES, initial={
            'username':request.POST['username']
        })
        if cuif.is_valid():
            request.user.username = cuif.cleaned_data['username']
            print(cuif.cleaned_data, "-----")
            request.user.head =  cuif.cleaned_data['head']
            request.user.save()
            return HttpResponse("保存成功")

        else:
            cuif = UserInfoChangeForm(initial={
                "username": request.user.username
            })
            return render(request, 'user/center.html', {'form': cuif})
    else:
        cuif = UserInfoChangeForm(initial={
            "username": request.user.username
        })
        return render(request, 'user/center.html', {'form':cuif})
def change_password(request):
    if request.method == 'POST':
        cgf = UserPassWordChangeForm(request.POST)
        if cgf.is_valid():
            if request.user.check_password(cgf.cleaned_data['old_password']):
                request.user.set_password(cgf.cleaned_data['password'])
                request.user.save()

                # 修改密码从新登录
                auth_logout(request)
                return redirect(reverse('user:login'))


            else:
                cgf.add_error("old_password", "原始密码不正确")
                return render(request, 'user/change_password.html', {"form": cgf})
        else:
            return render(request, 'user/change_password.html', {"form": cgf})
    else:
        cgf = UserPassWordChangeForm()
        return render(request, 'user/change_password.html', {"form": cgf})


def register(request):
    if request.method == "POST":
        rf = UserRegisterForm(request.POST)
        if rf.is_valid():
            user = rf.save(commit=False)
            user.set_password(rf.cleaned_data['password'])
            user.save()
            return redirect(reverse('user:login'))
        else:
            return render(request, 'user/register.html', {"form": rf})
    else:
        rf = UserRegisterForm()
        return render(request, 'user/register.html', {"form": rf})

def logout(request):
    auth_logout(request)
    return redirect(reverse('user:login'))
def login(request):
    if request.method == "POST":
        lf = UserLoginForm(request.POST)
        if lf.is_valid():
            user = CustomUser.objects.filter(username=lf.cleaned_data['username']).first()
            if user:
                if user.check_password(lf.cleaned_data['password']):
                    auth_login(request, user)
                    return redirect(reverse('main:index'))
                else:
                    lf.add_error("password", "密码错误")
                    return render(request, 'user/login.html', {"form": lf})
            else:
                lf.add_error("username", "用户名不存在")
                return render(request, 'user/login.html', {"form": lf})
        else:
            return render(request, 'user/login.html', {"form": lf})

    else:
        lf = UserLoginForm()
        return render(request, 'user/login.html', {"form": lf})



class ArticleCreateView(CreateView):
    # model = Article
    template_name = 'main/article_form.html'
    form_class = ArticleForm
    success_url =reverse_lazy('user:article_manage')
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class ArticleUpdateView(UpdateView):
    model = Article
    form_class = ArticleForm
    success_url = reverse_lazy('user:article_manage')

class ArticleDeleteView(DeleteView):
    model = Article
    success_url = reverse_lazy('user:article_manage')

class ArticleManageView(ListView):
    # model = Article
    template_name = 'user/article_manage.html'
    def get_queryset(self):
        return Article.objects.filter(author=self.request.user)
    paginate_by = 1
